import json
import asyncio
from .audio_processing_module import AudioProcessor, pcm_to_opus

# 录音处理模块：处理录制的音频数据和发送

class RecordingHandler:
    def __init__(self, recording_queue):
        self.recording_queue = recording_queue
    
    # 获取录制的音频数据
    def get_recorded_data(self):
        recorded_data = []
        while not self.recording_queue.empty():
            try:
                data = self.recording_queue.get_nowait()
                recorded_data.append(data)
                self.recording_queue.task_done()
            except:
                break
        return recorded_data
    
    # 发送录音数据到websocket
    async def send_recording_to_websocket(self, websocket, recorded_data):
        """将录制的音频数据发送到websocket"""
        print("[WEBSOCKET] 开始发送录音数据...")
        
        try:
            # 发送开始消息
            start_msg = {
                "type": "audio",
                "state": "start"
            }
            await websocket.send(json.dumps(start_msg))
            print("[WEBSOCKET] 已发送音频开始消息")
            
            # 创建音频处理器
            audio_processor = AudioProcessor(buffer_size=960)
            
            # 处理所有录音数据
            total_chunks = 0
            for audio_data in recorded_data:
                # 使用AudioProcessor处理音频数据
                chunks = audio_processor.process_audio(audio_data)
                for chunk in chunks:
                    # 转换为Opus格式
                    opus_data = pcm_to_opus(chunk)
                    if opus_data:
                        # 直接以二进制形式发送Opus数据
                        await websocket.send(opus_data)
                        total_chunks += 1
                        
                        # 每10个块显示一次进度
                        if total_chunks % 10 == 0:
                            print(f"[WEBSOCKET] 已发送 {total_chunks} 个Opus音频块")
            
            # 处理剩余数据
            remaining_chunks = audio_processor.process_remaining()
            for chunk in remaining_chunks:
                opus_data = pcm_to_opus(chunk)
                if opus_data:
                    await websocket.send(opus_data)
                    total_chunks += 1
            
            # 发送结束消息
            stop_msg = {
                "type": "audio",
                "state": "stop"
            }
            await websocket.send(json.dumps(stop_msg))
            
            print(f"[WEBSOCKET] 录音数据发送完成，共发送 {total_chunks} 个Opus音频块")
        except Exception as e:
            print(f"[ERROR] 发送录音数据时出错: {e}")
    
    # 清空录音队列
    def clear_recording_queue(self):
        if not self.recording_queue.empty():
            cleared_count = 0
            while not self.recording_queue.empty():
                try:
                    self.recording_queue.get_nowait()
                    self.recording_queue.task_done()
                    cleared_count += 1
                except Exception:
                    break
            print(f"[RECORD] 已清空录音队列中的 {cleared_count} 个数据块")
        else:
            print("录音队列为空，无需清理")
    
    # 分析录音数据（可选功能）
    def analyze_recording(self, recorded_data):
        """分析录音数据，返回统计信息"""
        if not recorded_data:
            return {"error": "没有录音数据"}
        
        total_bytes = sum(len(data) for data in recorded_data)
        duration_seconds = total_bytes / (960 * 2)  # 960样本/块，每样本2字节
        
        return {
            "total_blocks": len(recorded_data),
            "total_bytes": total_bytes,
            "estimated_duration_seconds": duration_seconds,
            "estimated_duration_formatted": f"{duration_seconds:.2f}秒"
        }